#include "stdafx.h"
#include "CMQTTClient.h"

#ifndef SENDER_NULL
#define SENDER_NULL nullptr
#endif // !SENDER_NULL



CMQTTClient::CMQTTClient() {
	initEvent();
}

CMQTTClient::~CMQTTClient() {
	Reset();
	removeEvent();
}

bool CMQTTClient::Init(const char* url, const char* clientId) {
	try {
		Reset();
		_client = new mqtt::client(url, clientId);
		_opts.set_keep_alive_interval(30);
		_opts.set_clean_session(false);
		_opts.set_connect_timeout(10);
		_sslopt.set_enable_server_cert_auth(false);
		_sslopt.set_ssl_version(MQTT_SSL_VERSION_DEFAULT);
		_opts.set_ssl(_sslopt);
		_opts.set_clean_start(true);
		_opts.set_mqtt_version(MQTTVERSION_3_1_1);
		_opts.set_user_name(clientId);
		_client->set_callback(*shared_from_this());

	}
	catch (const mqtt::persistence_exception& exc) {
		std::cout << "Init: " << exc.what();
		return false;
	}
	catch (const mqtt::exception& exc) {
		std::cout << "Init: " << exc.what();
		return false;
	}
	return true;

}

void CMQTTClient::Connect() {
	try {
		if (_client)
			_client->connect(_opts);
	}
	catch (const mqtt::persistence_exception& exc) {
		std::cout << "Connect: " << exc.what();
	}
	catch (const mqtt::exception& exc) {
		std::cout << "Connect: " << exc.what();
	}
}

void CMQTTClient::StartConnect() {
}

void CMQTTClient::connected(const std::string& cause) {
	std::cout << "connected" << cause << std::endl;
}

void CMQTTClient::connection_lost(const std::string& cause) {
	std::cout << "connection_lost: " << cause;
}

void CMQTTClient::message_arrived(mqtt::const_message_ptr msg) {

	std::cout << msg->get_payload_str() << std::endl;

	EventMQTTMsgArrived* evt_msg_arrived = new EventMQTTMsgArrived(SENDER_NULL);
	evt_msg_arrived->msg = msg;
	SNotifyCenter::getSingleton().FireEventAsync(evt_msg_arrived);
}

void CMQTTClient::delivery_complete(mqtt::delivery_token_ptr tok) {
	std::cout << "delivery_complete:" << tok->get_message()->get_payload() << std::endl;
}

void CMQTTClient::SendMsg(const char* topic, std::string& msg) {
	try {
		if (_client)
			_client->publish(topic, msg.c_str(), msg.size(), 2, false);
	}
	catch (const mqtt::exception& exc) {
		std::cout << "SendMsg: " << exc.what();
	}
}

inline void CMQTTClient::DisConnect() {
	if (_client)_client->disconnect();
}

mqtt::client* CMQTTClient::GetClient() {
	return _client;
}
